import sys
import re
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons

def plot_cpu_usage(file_path):
    # 初始化存储各个参数的列表
    time_series = []
    usr_list, sys_list, nic_list = [], [], []
    idle_list, io_list, irq_list, sirq_list = [], [], [], []
    
    # 读取文件并解析数据
    with open(file_path, 'r') as file:
        lines = file.readlines()
        time_index = 0  # 用于计算每5秒的时间
    
        for line in lines:
            # 匹配 "CPU: 55.8% usr 31.9% sys  0.0% nic  6.4% idle  0.0% io  4.1% irq  1.5% sirq" 格式的行
            match = re.search(r'CPU:\s+([\d.]+)% usr\s+([\d.]+)% sys\s+([\d.]+)% nic\s+([\d.]+)% idle\s+([\d.]+)% io\s+([\d.]+)% irq\s+([\d.]+)% sirq', line)
            if match:
                # 将解析的数值添加到各个列表
                usr_list.append(float(match.group(1)))
                sys_list.append(float(match.group(2)))
                nic_list.append(float(match.group(3)))
                idle_list.append(float(match.group(4)))
                io_list.append(float(match.group(5)))
                irq_list.append(float(match.group(6)))
                sirq_list.append(float(match.group(7)))
                
                # 添加当前时间点（以5秒为间隔）
                time_series.append(time_index)
                time_index += 5

    # 创建图表
    fig, ax = plt.subplots(figsize=(10, 6))
    plt.subplots_adjust(left=0.3)  # 调整图像空间以便放置勾选框

    # 绘制初始的CPU使用情况折线
    lines = []
    labels = ['usr', 'sys', 'nic', 'idle', 'io', 'irq', 'sirq']
    data_lists = [usr_list, sys_list, nic_list, idle_list, io_list, irq_list, sirq_list]

    for label, data in zip(labels, data_lists):
        line, = ax.plot(time_series, data, label=label, visible=True)  # 默认可见
        lines.append(line)

    # 设置图表标签
    ax.set_xlabel('Time (seconds)')
    ax.set_ylabel('CPU Usage (%)')
    ax.set_title('CPU Usage Over Time')
    ax.legend()
    ax.grid(True)

    # 添加勾选框
    rax = plt.axes([0.05, 0.4, 0.15, 0.4])  # 勾选框位置
    check = CheckButtons(rax, labels, [True] * len(labels))  # 默认全选

    # 定义勾选框点击事件
    def on_check(label):
        index = labels.index(label)
        lines[index].set_visible(not lines[index].get_visible())  # 切换线条可见性
        plt.draw()

    # 连接勾选框的事件
    check.on_clicked(on_check)

    plt.show()

# 主程序入口
if __name__ == '__main__':
    # 检查是否提供了文件路径参数
    if len(sys.argv) != 2:
        print("Usage: python top.py <file_path>")
    else:
        plot_cpu_usage(sys.argv[1])

